const Koa           = require('koa');
const koaStatic     = require('koa-static');
const cors          = require('koa2-cors'); // 跨域
const parameter     = require('koa-parameter'); // 参数校验
const koaBodyParser = require('koa-bodyparser');
const moogoose      = require('mongoose');
const error         = require('koa-json-error');

const config = require('./config');
const swagger= require('./plugins/swagger');
const router = require('./routes');
const app    = new Koa();

app.use(cors());
app.use(parameter(app));
app.use(error({
    postFormat(e, {stack, ...rest}) { 
        return process.env.NODE_ENV === 'production' ? rest : {stack, ...rest}
    }
}));
app.use(koaBodyParser());
app.use(swagger);
app.use(router.routes()).use(router.allowedMethods());

moogoose.connect(
    config.db.dsn, 
    { useNewUrlParser: true }, 
    ()=> {
        console.log("database connected!");
        app.listen(config.server.port,()=>{console.log(`Server started at port ${config.server.port}`)});
    });
moogoose.connection.on('error',console.error);
